import React, { useMemo } from 'react';
import {
    Form,
    Card,
    Button,
    Input,
    Tag,
    InputNumber,
    message,
    Select,
    Radio,
    Typography,
    Popover,
    Empty,
    Spin,
    Alert,
    ConfigProvider,
    Row,
    Col
} from 'antd';
import { history } from 'umi'
import { get as getPath } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction } from '@/components';
// import { AppellationSelect } from '@/pages/Organization/OrgFlow/components';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import LimitInput from '@/components/LimitInput';
import { FormHeader } from '@/molecules';
import EmployeeManage from '@/pages/Organization/OrgFlow/Department/components/EmployeeManage';
import { useRequest, useCurrentUser, useDraftStorage } from '@/hooks';
import { queryEmployeeFlagByType, confirmFlag } from '@/services/user';
import departmentGif from '@/assets/gif/departmentGif.gif';
import OrganizationSelect from '@/components/OrganizationSelect';
import { tree2array } from '@/utils/tree';
import {
    getDepartmentDetail,
    changeDepartmentToHistory,
    getRelativeOrganizations,
    getChildrenOrganizations,
    getLastOrgTree
} from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const { Option } = Select;

const getParentOrganizationName = (tagCode, orgList) => {
    const findItem = tree2array(orgList).find(e => e.organizationCode === tagCode);
    console.log(findItem, 'findItem');
    if (findItem && findItem.organizationName.indexOf('(审批中)') > -1) {
        return findItem.organizationName.replace('(审批中)', '');
    }
    return findItem.organizationName;
};

const DepartmentEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [loading, setLoading] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [info, setInfo] = React.useState(null);
    const [relativeList, setRelativeList] = React.useState([]);
    const [relativeSortList, setRelativeSortList] = React.useState([]);
    const [isAssistantFlag, setIsAssistantFlag] = React.useState(false);
    const [visible, setVisible] = React.useState(false);
    const [isAdjustDutyList, setIsAdjustDutyList] = React.useState(true);
    const { employeeCode } = useCurrentUser();

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('departmentadd');
    }, [location]);

    const { getDraft, setDraft, loading: draftLoading, draftUid } = useDraftStorage({
        uniqueId: query.organizationCode
    });

    const getDetail = async () => {
        setLoading(true);
        const res = await getDepartmentDetail(query && query.organizationCode);
        setLoading(false);
        const { data, code, msg } = res;
        if (code === 10000) {
            setInfo(data);
        } else {
            message.error(msg);
        }
    };

    const getRelativeList = async orgCode => {
        if (!orgCode) {
            return;
        }
        setLoading(true);
        const res = await getRelativeOrganizations(orgCode);
        const { data, code, msg } = res;
        if (code === 10000) {
            // console.log(data);
            setRelativeList((Array.isArray(data) && data) || []);
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    const getRelativeSortList = async orgCode => {
        if (!orgCode) {
            return;
        }
        setLoading(true);
        const res = await getChildrenOrganizations(orgCode);
        const { data, code, msg } = res;
        if (code === 10000) {
            setRelativeSortList((Array.isArray(data) && data) || []);
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    // 剔除当前组织查询剩余可选的机构树
    const { data: orgList, loading: orgLoading } = useRequest(() => getLastOrgTree(query?.organizationCode), {
        ready: !!query?.organizationCode
    });

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                // console.log('all');

                // 流程不存在提示
                const { workFlowUrl } = await hasWorkFlowByType('organizationApply', true, {
                    bizType: draftUid.draftType,
                    bizKey: draftUid.draftUniqueId
                });
                if (!workFlowUrl) {
                    return;
                }

                let subData;

                setSubmitLoading(true);
                if (isAddPage) {
                    subData = {
                        ...values,
                        organizationType: 3,
                        parentOrganizationPath: query && query.organizationPath,
                        parentOrganizationName: getPath(info, 'parentOrganizationName', ''),
                        operationType: 0,
                        parentOrganizationCode: query && query.organizationCode
                        // titleName: values.supervisorName.label,
                        // titleValue: values.supervisorName.key
                    };
                } else {
                    subData = {
                        organizationCode: getPath(info, 'organizationCode', ''),
                        ...values,
                        parentOrganizationPath: query && query.organizationPath,
                        parentOrganizationName: orgList?.data
                            ? getParentOrganizationName(values.parentOrganizationCode, orgList.data)
                            : '',
                        organizationType: 3,
                        operationType: 1
                        // parentOrganizationCode: info?.parentOrganizationCode
                        // titleName: values.supervisorName.label,
                        // titleValue: values.supervisorName.key
                    };
                }
                // 添加到历史记录表
                const { code, data: id, msg } = await changeDepartmentToHistory(subData || {});
                if (code === 10000) {
                    const otherParams = {};
                    if (!isAddPage) {
                        otherParams.organizationCode = query.organizationCode || '';
                    }
                    try {
                        await setDraft({ ...values, ...otherParams });
                    } catch (error) {
                        message.error(error.message);
                    }

                    history.push(`${workFlowUrl}${id}`);
                } else {
                    message.error(msg);
                }
                setSubmitLoading(false);
            }
        });
    };

    const handleRadioChange = event => {
        form.setFieldsValue({
            sort: event.target.value === 1 ? 999 : null,
            relativeOrganizations: [],
            relateOrganizationCodes: []
        });

        if (event.target.value === 1) {
            setIsAssistantFlag(true);
        } else {
            setIsAssistantFlag(false);
        }
    };

    const serverStorageKey = 'departmentEditKey';
    // 获取引导的flag
    const { data: flagVisible } = useRequest(() => queryEmployeeFlagByType(employeeCode, serverStorageKey), {
        ready: !!employeeCode,
        formatResult: res => {
            if (res) {
                const { code, data } = res;
                if (code === 10000) {
                    if (!data) {
                        setVisible(true);
                    }
                    return !data;
                }
            }
            return false;
        }
    });

    // 标记当前引导为已读
    const { run: readTips } = useRequest(() => confirmFlag(employeeCode, serverStorageKey), {
        manual: true,
        onSuccess: res => {
            const { code } = res;
            if (code === 10000) {
                setVisible(false);
            }
        }
    });

    React.useEffect(() => {
        const okCallback = result => {
            const { payload } = result.data;
            if (payload) {
                setInfo(payload);
            }
        };

        const cancelCallback = () => {
            getDetail();
        };

        const getDraftStorage = async () => {
            try {
                await getDraft(okCallback, isAddPage ? null : cancelCallback);
            } catch {
                if (!isAddPage) {
                    getDetail();
                }
            }
        };

        if (isAddPage) {
            getRelativeList(query && query.organizationCode);
            getRelativeSortList(query && query.organizationCode);
        }
        getDraftStorage();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    React.useEffect(() => {
        if (!isAddPage && info) {
            getRelativeList(getPath(info, 'parentOrganizationCode', ''));
            getRelativeSortList(getPath(info, 'parentOrganizationCode', ''));
            if (getPath(info, 'assistantFlag', '') === 1) {
                setIsAssistantFlag(true);
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [info]);

    const popoverContent = (
        <div style={{ minWidth: 250, maxWidth: 500, maxHeight: 250, overflow: 'auto' }}>
            {relativeSortList.map(item => (
                <div key={item.organizationCode} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography.Paragraph ellipsis>{item.organizationName}</Typography.Paragraph>
                    <div style={{ marginLeft: 10, marginRight: 10, flexShrink: 0, width: '6em' }}>
                        排序号：{item.sort}
                    </div>
                </div>
            ))}
            {relativeSortList.length <= 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
        </div>
    );
    // const getSupervisorValue = () => {
    //     if (info?.titleValue) {
    //         return {
    //             key: info?.titleValue,
    //             label: info?.titleName
    //         };
    //     }
    //     return undefined;
    // };

    //  当新增机构为上级机构的第一个子部门，该提示才出现
    const renderTipsDom = useMemo(() => {
        const messageNode = (
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <div className={styles.tipsDemo}>
                    <div className={styles.leftText}>
                        新增机构为上级机构的第一个子机构，则会默认承接上级机构除主管外的员工和岗位。
                    </div>
                    <Popover
                        content={
                            <div className={styles.popGif}>
                                <div className={styles.gifWrap}>
                                    <img src={departmentGif} alt="" />
                                </div>
                                <a
                                    onClick={() => {
                                        // 如果已经已读过了,则不再请求了.
                                        if (flagVisible) {
                                            readTips();
                                        } else {
                                            setVisible(false);
                                        }
                                    }}
                                >
                                    我知道了
                                </a>
                            </div>
                        }
                        placement={window.innerHeight > 750 ? 'bottomRight' : 'leftTop'}
                        trigger="click"
                        visible={visible}
                        getPopupContainer={trigger => trigger.parentNode}
                    >
                        <div
                            className={styles.rightClick}
                            onClick={() => {
                                setVisible(true);
                            }}
                        >
                            查看示例
                        </div>
                    </Popover>
                </div>
            </ConfigProvider>
        );

        return `${query?.showTips}` === 'true' ? (
            <Alert className={styles.alertCss} message={messageNode} type="info" showIcon banner />
        ) : null;
    }, [flagVisible, query, readTips, visible]);
    return (
        <PageHeaderWrapper>
            <Card
                title={
                    isAddPage ? (
                        '新增部门'
                    ) : (
                        <>
                            编辑部门
                            {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                                <Tag color="orange" style={{ marginLeft: 10 }}>
                                    {AUDIT[getPath(info, 'auditStatus', '')]}
                                </Tag>
                            )}
                        </>
                    )
                }
                bordered={false}
                // loading={loading}
                extra={
                    <BottomAction>
                        <CancelEditConfirm leaveConfirm>
                            <Button>取消</Button>
                        </CancelEditConfirm>
                        <Button
                            type="link"
                            style={{ border: '1px solid #FF9E00' }}
                            onClick={async () => {
                                const result = form.getFieldsValue();
                                const otherParams = {};
                                if (!isAddPage) {
                                    otherParams.organizationCode = query.organizationCode || '';
                                }
                                try {
                                    await setDraft({ ...result, ...otherParams });
                                    message.success('保存成功');
                                } catch (err) {
                                    message.error(err.message);
                                }
                            }}
                            loading={draftLoading}
                        >
                            保存
                        </Button>
                        <Button
                            type="primary"
                            disabled={getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2}
                            onClick={handleSubmit}
                            loading={submitLoading}
                        >
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                <Spin spinning={loading}>
                    {renderTipsDom}
                    <Form>
                        <div className={styles.formWrap}>
                            <Row type="flex" gutter="16">
                                <Col span={12}>
                                    <Form.Item label="上级机构">
                                        {isAddPage
                                            ? getPath(query, 'organizationName', '')
                                            : getFieldDecorator('parentOrganizationCode', {
                                                  initialValue: getPath(info, 'parentOrganizationCode', ''),
                                                  rules: [
                                                      {
                                                          required: true,
                                                          message: '上级机构不能为空'
                                                      }
                                                  ]
                                              })(
                                                  <OrganizationSelect
                                                      isStrictly
                                                      isNeedStatusPass
                                                      unLoading={orgLoading}
                                                      allowClear={false}
                                                      dropdownMatchSelectWidth
                                                      treeDataFromProp
                                                      treeDataList={orgList}
                                                      onChange={e => {
                                                          // 处理选择机构的时候变化的时候，管理情况不展示
                                                          if (e !== info?.parentOrganizationCode) {
                                                              setIsAdjustDutyList(false);
                                                          } else {
                                                              setIsAdjustDutyList(true);
                                                          }
                                                      }}
                                                  />
                                              )}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row type="flex" gutter="16">
                                <Col span={12}>
                                    <Form.Item label="部门名称(中文)">
                                        {getFieldDecorator('organizationName', {
                                            initialValue: getPath(info, 'organizationName', ''),
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '部门名称(中文)不能为空',
                                                    whitespace: true
                                                },
                                                {
                                                    validator(_, value, callback) {
                                                        if (value.indexOf('/') > -1) {
                                                            callback('不允许输入:或/');
                                                        } else if (value.indexOf(':') > -1) {
                                                            callback('不允许输入:或/');
                                                        } else {
                                                            callback();
                                                        }
                                                    }
                                                }
                                            ]
                                        })(<Input placeholder="请输入部门名称(中文)" allowClear maxLength={150} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label="部门名称(英文)">
                                        {getFieldDecorator('organizationNameEnglish', {
                                            initialValue: getPath(info, 'organizationNameEnglish', ''),
                                            rules: [
                                                {
                                                    validator(_, value, callback) {
                                                        if (value.indexOf('/') > -1 || value.indexOf(':') > -1) {
                                                            callback('不允许输入:或/');
                                                        } else {
                                                            callback();
                                                        }
                                                    }
                                                }
                                            ]
                                        })(<Input placeholder="请输入部门名称(英文)" allowClear maxLength={150} />)}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row type="flex" gutter="16">
                                <Col span={12}>
                                    <Form.Item label="排序号">
                                        <Popover
                                            content={popoverContent}
                                            title="当前排序"
                                            trigger="focus"
                                            placement="bottomRight"
                                            getPopupContainer={trigger => trigger.parentNode}
                                        >
                                            {getFieldDecorator('sort', {
                                                initialValue: getPath(info, 'sort', ''),
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '排序号不能为空'
                                                    }
                                                ]
                                            })(
                                                <InputNumber
                                                    min={1}
                                                    max={999}
                                                    precision={0}
                                                    disabled={isAssistantFlag}
                                                    placeholder="请输入排序号"
                                                    style={{ width: '100%' }}
                                                />
                                            )}
                                        </Popover>
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label="是否助理团">
                                        {getFieldDecorator('assistantFlag', {
                                            initialValue: getPath(info, 'assistantFlag', 0)
                                        })(
                                            <Radio.Group
                                                onChange={handleRadioChange}
                                                disabled={
                                                    !isAddPage ||
                                                    getPath(info, 'assistantFlag', 0) === 1 ||
                                                    relativeList.filter(item => item.assistantFlag === 1).length > 0
                                                }
                                            >
                                                <Radio value={0}>否</Radio>
                                                <Radio value={1}>是</Radio>
                                            </Radio.Group>
                                        )}
                                        {relativeList.filter(item => item.assistantFlag === 1).length > 0 && (
                                            <>当前层级已有助理团，不可新增</>
                                        )}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row type="flex" gutter="16">
                                <Col span={12}>
                                    <Form.Item label="关联机构">
                                        {getFieldDecorator('relateOrganizationCodes', {
                                            initialValue: getPath(info, 'relativeOrganizations', []).map(
                                                item => item.organizationCode
                                            )
                                        })(
                                            <Select
                                                mode="multiple"
                                                placeholder="请选择关联机构"
                                                getPopupContainer={trigger => trigger.parentNode}
                                            >
                                                {relativeList
                                                    .filter(
                                                        item =>
                                                            item.assistantFlag !== form.getFieldValue('assistantFlag')
                                                    )
                                                    .map(item => (
                                                        <Option
                                                            value={item.organizationCode}
                                                            key={item.organizationCode}
                                                        >
                                                            {item.organizationName}
                                                            {item?.auditStatus === 1 && '(审批中)'}
                                                        </Option>
                                                    ))}
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label="部门电话">
                                        {getFieldDecorator('phone', {
                                            initialValue: getPath(info, 'phone', ''),
                                            rules: [
                                                {
                                                    validator(rule, value, callback) {
                                                        const regex = /[a-zA-Z\u4e00-\u9fa5]+/g;
                                                        if (value && regex.test(value)) {
                                                            callback('部门电话不能包含中英文字符');
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })(<Input placeholder="请输入部门电话" allowClear maxLength={20} />)}
                                    </Form.Item>
                                </Col>
                            </Row>

                            {/* <Form.Item label="主管称呼">
                                {getFieldDecorator('supervisorName', {
                                    initialValue: getSupervisorValue(),
                                    rules: [
                                        {
                                            required: true,
                                            message: '主管称呼不能为空'
                                        }
                                    ]
                                })(<AppellationSelect />)}
                            </Form.Item> */}

                            <Form.Item label="部门简介(中文)">
                                {getFieldDecorator('organizationDesc', {
                                    initialValue: getPath(info, 'organizationDesc', '')
                                })(
                                    <LimitInput
                                        area
                                        maxLength={10000}
                                        autoSize={{ minRows: 5, maxRows: 20 }}
                                        placeholder="请输入部门简介(中文)"
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="部门简介(英文)">
                                {getFieldDecorator('organizationDescEnglish', {
                                    initialValue: getPath(info, 'organizationDescEnglish', '')
                                })(
                                    <LimitInput
                                        area
                                        maxLength={10000}
                                        autoSize={{ minRows: 5, maxRows: 20 }}
                                        placeholder="请输入部门简介(英文)"
                                    />
                                )}
                            </Form.Item>
                        </div>
                        {!isAddPage && (
                            <>
                                <FormHeader title="部门人员" id="employee-manage" />
                                {isAdjustDutyList ? (
                                    <Form.Item>
                                        {getFieldDecorator('adjustDutyList', {
                                            initialValue: getPath(info, 'adjustDutyList', [])
                                        })(<EmployeeManage organizationCode={query.organizationCode} />)}
                                    </Form.Item>
                                ) : (
                                    <div className={styles.nullList}>
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            description="修改上级机构后需审批通过后才可调整人员"
                                        />
                                    </div>
                                )}
                            </>
                        )}
                    </Form>
                </Spin>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(DepartmentEdit);
